package com.google.code.bankagregator.adapter.bank.imex.parser.deposit;

import com.google.code.bankagregator.adapter.exception.AdapterConnectException;
import com.google.code.bankagregator.entities.*;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * Created with IntelliJ IDEA.
 * User: kirill
 * Date: 14.06.13
 * Time: 4:29
 * To change this template use File | Settings | File Templates.
 */
public class ImexDepPatronParser {
    private static final String DEPOSIT_URL = "http://imexbank.com.ua/rus/all_deps.phtml#3w";
    private static final int TABLE_INDEX = 4;
    private static final int TERM_INDEX = 0;
    private static final int P_MIN_AMOUNT_INDEX = 2;
    private static final int TR_MIN_AMOUNT_INDEX = 6;
    private static final int TD_UAH_RATE_INDEX = 2;
    private static final int TD_USD_RATE_INDEX = 3;
    private static final int TD_EUR_RATE_INDEX = 4;
    private Document con = null;
    private Bank bank = null;

    public ImexDepPatronParser() throws AdapterConnectException {
        bank = new Bank();
        bank.setName("АО \"ИМЭКСБАНК\"");
        bank.setUrl("http://imexbank.com.ua/rus/main.phtml");
        try {
            con = Jsoup.connect(DEPOSIT_URL).timeout(5000).get();
        } catch (IOException e) {
            throw new AdapterConnectException(e.getMessage());
        }
    }

    /**
     * Get UAH deposit`s params (Постоянный клиент)
     *
     * @return UAH deposit`s params
     * @throws AdapterConnectException
     */
    public List<Deposit> getUAHDeposit() throws AdapterConnectException {
        Element minAmountEl = con.select("div.about_content table").get(TABLE_INDEX).select("tr").
                get(TR_MIN_AMOUNT_INDEX).select("td").first().select("p").get(P_MIN_AMOUNT_INDEX);
        int minAmount = Integer.parseInt(minAmountEl.text().substring(23, 27));
        List<Deposit> depositParam = new ImexDepPatronParser().parser(minAmount, TD_UAH_RATE_INDEX, Currency.UAH);
        return depositParam;
    }

    /**
     * Get USD deposit`s params
     *
     * @return USD deposit`s params
     * @throws AdapterConnectException
     */
    public List<Deposit> getUSDDeposit() throws AdapterConnectException {
        Element minAmountEl = con.select("div.about_content table").get(TABLE_INDEX).select("tr").
                get(TR_MIN_AMOUNT_INDEX).select("td").first().select("p").get(P_MIN_AMOUNT_INDEX);

        int minAmount = Integer.parseInt(minAmountEl.text().substring(35, 38));
        List<Deposit> depositParam = new ImexDepPatronParser().parser(minAmount, TD_USD_RATE_INDEX, Currency.USD);
        return depositParam;

    }

    /**
     * Get EUR deposit`s params
     *
     * @return deposit`s params
     * @throws AdapterConnectException
     */
    public List<Deposit> getEURDeposit() throws AdapterConnectException {
        Element minAmountEl = con.select("div.about_content table").get(TABLE_INDEX).select("tr").
                get(TR_MIN_AMOUNT_INDEX).select("td").first().select("p").get(P_MIN_AMOUNT_INDEX);
        int minAmount = Integer.parseInt(minAmountEl.text().substring(50, 53));
        List<Deposit> depositParam = new ImexDepPatronParser().parser(minAmount, TD_EUR_RATE_INDEX, Currency.EUR);
        return depositParam;

    }

    /**
     * Get some deposit`s params
     *
     * @param minAmount
     * @param tdRateIndex - index for the rate`s counting
     * @param currency
     * @return some deposit`s params
     */
    public List<Deposit> parser(int minAmount, int tdRateIndex, Currency currency) {
        List<Deposit> depositParam = new ArrayList<>();
        Pattern p = Pattern.compile("(»|«)");
        Matcher matcher = null;

        Element nameEL = con.select("div.about_content table").get(TABLE_INDEX).select("th").
                first();
        matcher = p.matcher(nameEL.text());
        String name = matcher.replaceAll("").trim();

        Integer[] tableLinesWithTerm = new Integer[]{2, 3, 4, 5};

        for (int line : tableLinesWithTerm) {
            Deposit deposit = new Deposit();
            Element termEl = con.select("div.about_content table").get(TABLE_INDEX).select("tr").
                    get(line).select("td:not([rowspan=4])").first();
            String[] StringsWithTerms = termEl.text().split(" ");

            Element rateEl = con.select("div.about_content table").get(TABLE_INDEX).select("tr").
                    get(line).select("td:not([rowspan=4])").get(tdRateIndex);


            double rate = Double.parseDouble(rateEl.text().replace(",", "."));
            int term = Integer.parseInt(StringsWithTerms[TERM_INDEX]) * 31;

            deposit.setType(DepositType.Deposit);
            deposit.setMinAmount(minAmount);
            deposit.setDepositRate(rate);
            deposit.setTerm(term);
            deposit.setRefill(true);
            deposit.setName(name);
            deposit.setCurrency(currency);
            deposit.setUrl(DEPOSIT_URL);
            deposit.setBank(bank);
            deposit.setState(State.ACTIVE);
            depositParam.add(deposit);
        }
        return depositParam;
    }
}
